package imsdk

import (
	"encoding/json"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/http"
)

type GroupForbidMsgReq struct {
	MembersAccount []string `json:"Members_Account"`
	MuteTime       int64    `json:"MuteTime"` //0表示取消该帐号的群组消息禁言 , 4294967295表示该帐号被设置永久禁言
	GroupId        string   `json:"GroupId"`
}
type GroupForbidMsgResp struct {
	ErrorInfo    string `json:"ErrorInfo"`
	ErrorCode    int    `json:"ErrorCode"`
	ActionStatus string `json:"ActionStatus"`
}

// GroupForbidMsg 在某个群组里禁言
func (s sdk) GroupForbidMsg(groupId string, userId string, tBan int64) error {
	reqUrl := s.BuildRestfulUrl("/group_open_http_svc/forbid_send_msg")

	req := GroupForbidMsgReq{}
	//tBan为0就是解除
	req = GroupForbidMsgReq{GroupId: groupId, MuteTime: tBan}
	req.MembersAccount = make([]string, 0)
	req.MembersAccount = append(req.MembersAccount, userId)

	bytes, _ := json.Marshal(req)

	global.Log.Debugf("===GroupForbidMsg ===  reqUrl: %s, req: %s", reqUrl, string(bytes))
	result, err := http.HttpPost(reqUrl, string(bytes), connTimeoutMs, serveTimeoutMs, "application/json")
	if err != nil {
		global.Log.Errorf("ban user - http IM error: %s", err)
		return err
	}

	resp := GlobalForbidMsgResp{}

	global.Log.Debugf("===GroupForbidMsg ===  result: %s", string(result))
	err = json.Unmarshal(result, &resp)
	if err != nil {
		global.Log.Errorf("ban user - unmarshal IM resp error: %s", err)
		return err
	}

	if resp.ErrorCode != 0 {
		global.Log.Errorf("ban user - IM resp error: %s, error code: %v", resp.ErrorInfo, resp.ErrorCode)
		return fmt.Errorf(resp.ErrorInfo)
	}
	return nil
}
